#include "historymessagewidget.h"
#include "debug.h"
#include "model/datacenter.h"
#include "toast.h"
#include <QScrollArea>
#include <QGridLayout>
#include <QFileDialog>
#include <QDateTime>
#include <QPushButton>
#include <QStackedWidget>
#include <QScrollBar>
#include <QTableWidget>
#include <QHeaderView>
#include <QCalendar>
#include <QCalendarWidget>
#include <QMenu>

using namespace model;

/*-------------------------------- 历史消息窗口 --------------------------------*/
HistoryMessageWidget::HistoryMessageWidget(QWidget* parent) : QDialog(parent) {
    // 1. 设置窗口本身属性
    this->setFixedSize(600, 620);
    this->setWindowTitle("历史消息");
    this->setWindowIcon(QIcon(":/resource/image/logo.png"));
    this->setStyleSheet("QWidget { background-color: rgb(255, 255, 255); }");
    this->setAttribute(Qt::WA_DeleteOnClose);

    // 2. 创建主布局管理器.
    QGridLayout* layout = new QGridLayout();
    layout->setSpacing(10);
    layout->setContentsMargins(30, 30, 20, 0);
    this->setLayout(layout);

    // 3. 创建单选按钮
    QString radioBtnStyle = QString(R"(
        QRadioButton::indicator {
            width: 14px;  /* 控制指示器（圆圈）的宽度 */
            height: 14px; /* 控制指示器（圆圈）的高度 */
            border-radius: 7px;
        }
        QRadioButton::indicator:unchecked {
            background-color: white;
            border: 1px solid #999;
        }
        QRadioButton::indicator:checked {
            background-color: #07c160;
            border: 1px solid #07c160;
        }
        QRadioButton::indicator:checked:hover {
            background-color: #06ad56;
            border: 1px solid #06ad56;
        }
        QRadioButton {
            padding-left: 3px;
            spacing: 5px;
            font-size: 14px;
        }
    )");

    keyRadioBtn = new QRadioButton("按关键词查询");
    keyRadioBtn->setStyleSheet(radioBtnStyle);
    timeRadioBtn = new QRadioButton("按时间查询");
    timeRadioBtn->setStyleSheet(radioBtnStyle);
    keyRadioBtn->setChecked(true); // 默认按关键词查询

    // 4. 创建 QStackedWidget 和其页面
    QStackedWidget* stackedWidget = new QStackedWidget(this);
    stackedWidget->setCurrentIndex(0); // 初始显示关键词页面

    // 4.1. 创建关键词搜索页面
    QWidget* keywordPage = new QWidget(this);
    QHBoxLayout* keywordLayout = new QHBoxLayout(keywordPage);
    keywordLayout->setContentsMargins(0, 0, 0, 0);
    keywordLayout->setSpacing(0); // 根据需要调整间距
    searchEdit = model::createSearchBox(50, "要搜索的关键词", 14);
    keywordLayout->addWidget(searchEdit, 1); // 占据大部分空间，以便搜索按钮在其右侧
    stackedWidget->addWidget(keywordPage); // 添加关键词页面到栈

    // 4.2. 创建时间搜索页面
    QWidget* timePage = new QWidget(this);
    QHBoxLayout* timeLayout = new QHBoxLayout(timePage);
    timeLayout->setContentsMargins(0,0,0,0); // 页面内部内容与边界的距离
    timeLayout->setSpacing(5); // 控件之间的水平间距

    // 4.2.1 时间标签
    QLabel* begTag = new QLabel("开始时间");
    begTag->setStyleSheet("font-size: 12px; color: #333;");
    QLabel* endTag = new QLabel("结束时间");
    endTag->setStyleSheet(begTag->styleSheet());

    // 4.2.2 时间编辑框
    begTimeEdit = createTimeArea();
    endTimeEdit = createTimeArea();

    // 4.2.3 搜索按钮
    QPushButton* searchBtn = new QPushButton("搜索");
    searchBtn->setFixedSize(80, 40);
    searchBtn->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
    searchBtn->setStyleSheet(R"(
        QPushButton { border: none; background-color: #EAEAEA; border-radius: 5px; font-size: 14px}
        QPushButton:hover { background-color: rgb(210, 210, 210); }
        QPushButton:pressed { background-color: rgb(173, 173, 173); }
    )");

    // 4.2.4 将控件添加到布局 布局比例分配：标签占固定宽度，时间编辑框占据剩余空间，搜索按钮固定宽度
    timeLayout->addWidget(begTag);
    timeLayout->addWidget(begTimeEdit, 1); // 伸缩因子为1，占据更多空间
    timeLayout->addSpacing(15); // 增加“开始时间”和“结束时间”之间的间距
    timeLayout->addWidget(endTag);
    timeLayout->addWidget(endTimeEdit, 1); // 伸缩因子为1，占据更多空间
    timeLayout->addSpacing(20); // 增加时间编辑框和搜索按钮之间的间距

    timeLayout->addWidget(searchBtn); // 搜索按钮也在这里复用
    stackedWidget->addWidget(timePage); // 添加时间页面到栈

    // 5. 布局占位
    layout->addWidget(keyRadioBtn, 0, 0, 1, 2);
    layout->addWidget(timeRadioBtn, 0, 2, 1, 2);
    layout->addWidget(stackedWidget, 1, 0, 1, 9); // 将 QStackedWidget 添加到主布局的第二行，跨越所有列

    // 6. 创建滚动区域
    initScrollArea(layout);

    // 7. 设置槽函数 (修改为切换 QStackedWidget 索引)
    connect(keyRadioBtn, &QRadioButton::clicked, this, [=](){
        stackedWidget->setCurrentIndex(0); // 切换到关键词搜索页面 (索引0)
    });
    connect(timeRadioBtn, &QRadioButton::clicked, this, [=](){
        stackedWidget->setCurrentIndex(1); // 切换到时间搜索页面 (索引1)
    });

    // 连接搜索信号
    // connect(searchEdit, &QLineEdit::returnPressed, this, [=](){
    //     qDebug() << "关键词搜索：" << searchEdit->text();
    // });
    // connect(searchBtn, &QPushButton::clicked, this, [=](){
    //     qDebug() << "时间搜索：从" << begTimeEdit->dateTime() << "到" << endTimeEdit->dateTime();
    // });

    connect(searchEdit, &QLineEdit::returnPressed, this, &HistoryMessageWidget::clickSearchBtn);
    connect(searchBtn, &QPushButton::clicked, this, &HistoryMessageWidget::clickSearchBtn);

#if TEST_UI
    for(int i = 0; i < 30; ++i){
        UserInfo sender;
        sender.userId = "";
        sender.nickname = "张三" + QString::number(i);
        sender.avatar = QIcon(":/resource/image/shuizhu.png");
        sender.description = "";
        sender.phone = "186 1234 5678";
        Message message = Message::makeMessage(TEXT_TYPE, "", sender, QString("消息内容" + QString::number(i)).toUtf8(), "");
        this->addHistoryMessage(message);
    }
#endif
}

void HistoryMessageWidget::addHistoryMessage(const Message &message){
    HistoryItem* historyItem = HistoryItem::makeHistoryItem(message);
    container->layout()->addWidget(historyItem);
}

void HistoryMessageWidget::clear(){
    QVBoxLayout* layout = dynamic_cast<QVBoxLayout*>(container->layout());
    for(int i = layout->count() - 1; i >= 0; --i){
        QWidget* w = layout->itemAt(i)->widget();
        if(w == nullptr) continue;
        layout->removeWidget(w);
        w->deleteLater();
    }
}

void HistoryMessageWidget::clickSearchBtn(){
    DataCenter* dataCenter = DataCenter::getInstance();
    connect(dataCenter, &DataCenter::searchMessageDone, this, &HistoryMessageWidget::clickSearchBtnDone, Qt::UniqueConnection);

    if (keyRadioBtn->isChecked()) {
        // 按照关键词搜索
        const QString& searchKey = searchEdit->text();
        if (searchKey.isEmpty()) {
            return;
        }
        dataCenter->searchMessageAsync(searchKey);
    } else {
        // 按照时间搜索
        auto begTime = begTimeEdit->dateTime();
        auto endTime = endTimeEdit->dateTime();
        if (begTime >= endTime) {
            Toast::showMessage("时间错误! 开始时间大于结束时间!");
            return;
        }
        dataCenter->searchMessageByTimeAsync(begTime, endTime);
    }
}

void HistoryMessageWidget::clickSearchBtnDone(){
    // 1. 从 DataCenter 中拿到消息搜索的结果列表
    DataCenter* dataCenter = DataCenter::getInstance();
    QList<Message>* messageResult = dataCenter->getSearchMessageResult();
    if (messageResult == nullptr) {
        return;
    }

    // 2. 把结果列表的数据, 显示到界面上
    this->clear();
    for (const Message& m : *messageResult) {
        this->addHistoryMessage(m);
    }
}

void HistoryMessageWidget::initScrollArea(QGridLayout *layout)
{
    // 1. 创建滚动界面 QWidget
    container = new QWidget();
    container->setObjectName("historyMessageContainer");
    container->setStyleSheet("#historyMessageContainer{ background-color: transparent;} ");

    // 2. 创建滚动区域对象
    QScrollArea* scrollArea = model::createScrollArea();
    scrollArea->setWidget(container);
    layout->addWidget(scrollArea, 2, 0, 1, 9);
    layout->setRowStretch(2, 1);

    // 3. 创建 container 里的容器
    QVBoxLayout* vlayout = new QVBoxLayout();
    vlayout->setSpacing(10);
    vlayout->setContentsMargins(0, 0, 0, 0);
    vlayout->setAlignment(Qt::AlignTop);
    container->setLayout(vlayout);
}

QDateTimeEdit* HistoryMessageWidget::createTimeArea()
{
    QDateTimeEdit* dateTimeEdit = new QDateTimeEdit();
    dateTimeEdit->setFixedHeight(40);
    dateTimeEdit->setDisplayFormat("yyyy-MM-dd hh:mm");
    dateTimeEdit->setCalendarPopup(true);
    dateTimeEdit->setDateTime(QDateTime::currentDateTime());
    dateTimeEdit->setStyleSheet(R"(
        QDateTimeEdit{
            border-radius: 5px;
            background-color: white;
            font-size: 12px;
        }
        /* 下拉按钮样式 */
        QDateTimeEdit::drop-down {
            width: 20px;
            border-left: 1px solid #DDD;
            border-top-right-radius: 5px;
            border-bottom-right-radius: 5px;
        }
        QDateTimeEdit::drop-down:hover {
            background-color: #F5F5F5;
        }
        QDateTimeEdit::down-arrow {
            image: url(:/resource/image/arrow_down.png);
            width: 12px;
            height: 12px;
        }
        QDateTimeEdit {
            border: 1px solid #EAEAEA;
            padding: 5px;
            background-color: #F7F7F7;
        }
        QDateTimeEdit:focus {
            border: 1px solid #07c160;
            background-color: white;
        }
    )");

    QString calendarStyle = R"(
        QCalendarWidget {
            border-radius: 5px;
            background-color: white;
            font-size: 12px;
            border: 1px solid #E0E0E0;
        }

        /* 导航按钮样式 */
        QCalendarWidget QToolButton {
            background-color: #F7F7F7;
            color: #333;
            border: 1px solid #E0E0E0;
            border-radius: 3px;
            padding: 2px 5px;
            margin: 2px;
        }
        QCalendarWidget QToolButton:hover {
            background-color: #E9E9E9;
        }
        QCalendarWidget QToolButton#qt_calendar_prevmonth {
            qproperty-icon: url(:/resource/image/arrow_left.png);
        }
        QCalendarWidget QToolButton#qt_calendar_nextmonth {
            qproperty-icon: url(:/resource/image/arrow_right.png);
        }
        QCalendarWidget QToolButton::menu-indicator {
            image: none;
        }
        /* 表格视图 */
        QCalendarWidget QTableView {
            gridline-color: #EEE;
            alternate-background-color: white;
            border: none;
        }
        QCalendarWidget QAbstractItemView {
            outline: none;
        }

        /* 周标题样式 */
        QCalendarWidget QHeaderView::section {
            background-color: #F7F7F7;
            color: #333;
            font-weight: normal;
            padding: 5px 0;
            border: none;
        }

        /* 日期单元格样式 */
        QCalendarWidget QAbstractItemView:item {
            background-color: white;
            border: none;
        }
        QCalendarWidget QAbstractItemView:item:selected {
            background-color: #07c160;
            color: white;
            border-radius: 3px;
        }
        QCalendarWidget QAbstractItemView:item:hover {
            background-color: #E9F8F0;
        }

        /* 今天日期样式 */
        QCalendarWidget QAbstractItemView:item.QCalendarWidget::Today {
            background-color: #F0F0F0;
            border: 1px solid #DDD;
            color: #333;
            font-weight: bold;
        }
        QCalendarWidget QAbstractItemView:item.QCalendarWidget::Today:selected {
            background-color: #06b055;
            color: white;
        }
    )";

    dateTimeEdit->calendarWidget()->setStyleSheet(calendarStyle);

    // 设置周显示为单字
    dateTimeEdit->calendarWidget()->setHorizontalHeaderFormat(QCalendarWidget::SingleLetterDayNames);

    // 设置中文Locale并简化显示
    QLocale chineseLocale(QLocale::Chinese, QLocale::China);
    dateTimeEdit->calendarWidget()->setLocale(chineseLocale);
    dateTimeEdit->calendarWidget()->setFirstDayOfWeek(Qt::Monday); // 设置周一为每周第一天

    // 优化月份选择器
    QCalendarWidget* calendar = dateTimeEdit->calendarWidget();
    calendar->setVerticalHeaderFormat(QCalendarWidget::NoVerticalHeader); // 隐藏周数
    calendar->setGridVisible(false); // 隐藏网格线

    // 设置月份选择器的弹出菜单
    QMenu* monthMenu = calendar->findChild<QMenu*>();
    if (monthMenu) {
        monthMenu->setStyleSheet(R"(
            QMenu {
                background-color: white;
                border: 1px solid #E0E0E0;
                border-radius: 5px;
                padding: 5px;
            }
            QMenu::item {
                padding: 5px 15px;
                border-radius: 3px;
            }
            QMenu::item:selected {
                background-color: #07c160;
                color: white;
            }
        )");
    }

    return dateTimeEdit;
}

/*-------------------------------- 一个历史消息元素 --------------------------------*/
HistoryItem *HistoryItem::makeHistoryItem(const Message &message)
{
    // 1. 创建出对象
    HistoryItem* item = new HistoryItem();
    item->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);// 这里高度不能固定

    // 2. 创建布局
    QGridLayout* layout = new QGridLayout();
    layout->setVerticalSpacing(0);
    layout->setHorizontalSpacing(10);
    layout->setContentsMargins(0, 0, 0, 0);
    item->setLayout(layout);

    // 3. 创建头像
    QPushButton* avatarBtn = new QPushButton();
    avatarBtn->setFixedSize(40, 40);
    avatarBtn->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
    avatarBtn->setIconSize(QSize(40, 40));
    // 当前消息发送者的头像
    QPixmap pixmap = message.sender.avatar.pixmap(40, 40);
    pixmap = model::getRoundRectPixmap(pixmap, QSize(40, 40), 8);
    avatarBtn->setIcon(pixmap);
    avatarBtn->setStyleSheet("QPushButton { border: none; }");

    // 4. 创建昵称和时间
    QLabel* nameLabel = new QLabel();
    nameLabel->setText(message.sender.nickname + " | " + message.time);
    nameLabel->setFixedHeight(20);   // 高度设置为头像高度的一半
    nameLabel->setStyleSheet("QLabel { font: 400 11px 'Microsoft YaHei'; color: #666; }");
    nameLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);

    // 5. 消息内容部分
    QWidget* contentWidget = nullptr;
    if (message.messageType == TEXT_TYPE) {
        // 文本消息
        QLabel* label = new QLabel();
        label->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
        label->setWordWrap(true); // 自动换行
        label->setText(QString(message.content));
        label->setStyleSheet(R"(
            QLabel {
                font: 400 14px 'Microsoft YaHei';
                color: #333;
                line-height: 1.2;
                background-color: transparent;
            }
        )");
        label->setTextInteractionFlags(Qt::TextSelectableByMouse); // 允许复制
        label->adjustSize();	// 设置让 label 能够自动调整大小
        contentWidget = label;
    } else if (message.messageType == IMAGE_TYPE) {
        // 图片消息
        // contentWidget = new ImageButton(message.fileId, message.content);
    } else if (message.messageType == FILE_TYPE) {
        // 文件消息
        // contentWidget = new FileLabel(message.fileId, message.fileName);
    } else if (message.messageType == SPEECH_TYPE) {
        // 语音消息
        // contentWidget = new SpeechLabel(message.fileId);
    } else {
        LOG() << "错误的消息类型! messageType=" << message.messageType;
    }

    // 6. 把上述控件添加到布局中
    layout->addWidget(avatarBtn, 0, 0, 2, 1);
    layout->addWidget(nameLabel, 0, 1, 1, 1);
    layout->addWidget(contentWidget, 1, 1, 5, 1);

    return item;
}






















